"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const react_navigation_redux_helpers_1 = require("react-navigation-redux-helpers");
const react_navigation_1 = require("react-navigation");
const react_native_1 = require("react-native");
const store_1 = require("../../store");
const action_1 = require("../../action");
const route_1 = require("../../../constants/route");
const utils = require("../../../utils");
react_native_1.BackHandler.addEventListener('hardwareBackPress', () => {
    store_1.store.dispatch(hardwareBackAction());
    return true;
});
const PREV_CHECK_TIME = {};
const CHECK_INTERVAL = 650;
function checkInterval(type, force) {
    const now = Date.now();
    const prev = PREV_CHECK_TIME[type] ? PREV_CHECK_TIME[type] : 0;
    if (force || (now >= prev)) {
        PREV_CHECK_TIME[type] = now + CHECK_INTERVAL;
        return true;
    }
    return false;
}
exports.connect = (dispatch, connected, mapKeys) => (Object.assign({}, connected, { _u_nav_navTo: (routeName, params, force) => checkInterval(0, force) && dispatch(navToAction(routeName, params)), _u_nav_navBack: (force) => checkInterval(1, force) && dispatch(navBackAction()) }));
const navToAction = (routeName, params) => {
    return (dispatch, getState) => {
        dispatch(react_navigation_1.NavigationActions.navigate({ routeName, params }));
    };
};
let appExit = false;
let appExitTimeHandler = 0;
const hardwareBackAction = () => {
    return (dispatch, getState) => {
        const action = {
            type: action_1.HardwareBackType,
            back: {},
        };
        const { routes } = exports.appStackSelector(getState());
        if (utils.getLength(routes) <= 1) {
            action.back.appExit = true;
        }
        dispatch(action);
        if (action.back.appExit) {
            if (appExit) {
                react_native_1.BackHandler.exitApp();
            }
            else {
                appExit = true;
                appExitTimeHandler && clearTimeout(appExitTimeHandler);
                appExitTimeHandler = setTimeout(() => {
                    appExit = false;
                }, 3000);
            }
        }
        else if (!action.back.ignore) {
            dispatch(navBackAction());
        }
    };
};
const navBackAction = () => react_navigation_1.NavigationActions.back();
const _navReducer = react_navigation_redux_helpers_1.createNavigationReducer(route_1.AppStack);
function navReducer(state, action) {
    return _navReducer(state, action);
}
exports.navReducer = navReducer;
exports.appStackSelector = (state) => state.ui.nav;
